<template>
	<el-form :model="form" :rules="rules" ref="formRef" label-width="0">
		<el-form-item prop="reason">
			<el-input type="textarea" v-model="form.reason" :placeholder="placeholder" :rows="4" maxlength="200" show-word-limit style="width: 100%" />
		</el-form-item>
		<div style="text-align: right; margin-top: 10px">
			<el-button @click="onCancel">取消</el-button>
			<el-button type="primary" :loading="loading" @click="onSubmit">{{ buttonText }}</el-button>
		</div>
	</el-form>
</template>

<script setup lang="ts">
import { ref, defineProps, defineEmits, computed } from 'vue';

const props = defineProps({
	title: { type: String, default: '审批原因' },
	placeholder: { type: String, default: '请输入审批原因' },
	buttonText: { type: String, default: '提交' },
	defaultReason: { type: String, default: '' },
	isRequired: { type: Boolean, default: false }, // 新增：控制是否必填
	wtmdata: { type: Object, default: () => ({}) }, // 从openDialog传递的数据
});

// 从wtmdata中获取isRequired属性
const isRequiredFromWtmdata = computed(() => props.wtmdata?.isRequired || props.isRequired);

const emit = defineEmits(['submit', 'cancel', 'closeDialog']);
const formRef = ref();
const loading = ref(false);
const form = ref({ reason: props.defaultReason });

// 动态计算验证规则
const rules = computed(() => {
	const baseRules: any[] = [{ min: 2, max: 200, message: '2-200字', trigger: 'blur' }];

	// 只有在必填时才添加required规则
	if (isRequiredFromWtmdata.value) {
		baseRules.unshift({ required: true, message: '请输入审批原因', trigger: 'blur' });
	}

	return {
		reason: baseRules,
	};
});

function onSubmit() {
	formRef.value.validate((valid: boolean) => {
		if (valid) {
			loading.value = true;
			emit('submit', form.value.reason);
			emit('closeDialog');
			loading.value = false;
		}
	});
}
function onCancel() {
	emit('cancel');
	emit('closeDialog');
}
</script>
